var connectInfo = null //连接中的蓝牙
var BLData = {
	openOK: false, //蓝牙是否打开
	BLZT: false, //蓝牙状态是否可用
	BLSO: false, //蓝牙是否正在搜索
	TS: "开始初始化蓝牙模块...",
}
var lianjieing = false; //记录是否正在尝试连接
var dayinji = {
	status: 0,
	uuid: "",
	suuid: "",
	nuuid: ""
} //已连接的蓝牙设备 uuid
var BLSB = new Array(); //记录已搜索到的蓝牙设备

function GETData() {
	return BLData;
}

function GETSB() {
	return BLSB;
}

function chonglian(back) {
	if (dayinok == true) {
		back('ok');
		return;
	}
	if (lianjieing == true) {
		back("正在尝试连接请稍后");
		return;
	}
	try {
		var value = wx.getStorageSync('dayinji')
		if (value) {
			//重新初始化蓝牙
			wx.openBluetoothAdapter({
				success: function(res) {
					lianjie(value.uuid, back); //成功则开始连接
				},
				fail: function(res) {
					lianjieing = false;
					back('请先打开蓝牙');
					BLData.TS = "请先打开蓝牙开关!"
				}
			})
		}
	} catch (e) {
		console.log("读取缓存数据错误:", e)
	}

}
// 充值参数
function reset() {
	console.log('resset--')
	connectInfo = null //连接中的蓝牙
	dayinji = {
		status: 0,
		uuid: "",
		suuid: "",
		nuuid: ""
	} //已连接的蓝牙设备 uuid
	BLData = {
		openOK: false, //蓝牙是否打开
		BLZT: false, //蓝牙状态是否可用
		BLSO: false, //蓝牙是否正在搜索
		TS: "开始初始化蓝牙模块...",
	}
	lianjieing = false; //记录是否正在尝试连接

	BLSB = new Array(); //记录已搜索到的蓝牙设备
}
// 打开蓝牙,蓝牙初始化
function openBlueTooth(successCallback, failCallback) {
	// let syssetting = uni.getSystemSetting()
	// if (!syssetting.bluetoothEnabled) {
	// 	BLData.TS = "请先打开蓝牙开关!"
	// 	console.log(uni.getSystemSetting())
	// 	return failCallback({
	// 		errno: 0,
	// 		errMsg: '请先打开蓝牙开关'
	// 	})
	// }
	uni.closeBluetoothAdapter({
		success: function(res) {
			//初始化蓝牙模块
			uni.openBluetoothAdapter({
				success: function(res) {
					if (res.errMsg == "openBluetoothAdapter:ok") {
						BLData.openOK = true
						BLData.TS = "蓝牙模块初始化成功!"
						successCallback()
					} else {
						console.log(res)
						BLData.TS = "请先打开蓝牙开关!"
					}
				},
				fail: function(res) {
					failCallback(res)
				}
			})
		},
		fail(res) {
			console.log(res)
			failCallback(res)
		}
	})
}

// 验证蓝牙适配器，监听蓝牙适配器
function checkBluetoothAdapterState(callback, onBluetoothAdapterStateChange = '') {
	//获取本机蓝牙适配器状态
	uni.getBluetoothAdapterState({
		success: function(res) {
			if (res.available) {
				BLData.BLZT = true;
				BLData.TS = "蓝牙适配器状态可用";
			}
		}
	})
	//监听本机蓝牙适配器变化(蓝牙状态变化时触发)
	uni.onBluetoothAdapterStateChange(function(res) {
		if (res.available) {
			BLData.BLZT = true;
			BLData.TS = "蓝牙适配器状态可用";
		} else {
			BLData.BLZT = false;
			BLData.TS = "蓝牙适配器当前不可用";
		}
		if (onBluetoothAdapterStateChange != '') {
			onBluetoothAdapterStateChange(res)
		}
	})
	BLData.TS = "蓝牙设备搜索中";
	setTimeout((res) => {
		callback()
	}, 500)

}

// 搜索蓝牙设备
function searchDevices(onDeviceFound, option = {}, num = 0) {
	if (!BLData.BLZT) {
		console.log('searchDevices', BLData.BLZT)
		if (num < 1) {
			setTimeout((res) => {
				return searchDevices(onDeviceFound, option, num++)
			}, 1000)
		}
		return false
	}
	BLData.TS = "蓝牙设备搜索中";
	BLSB = new Array();
	stopsearch(function() {
		BLData.BLSO = true
		uni.startBluetoothDevicesDiscovery({
			success: function(res) {
				if (res.errMsg == "startBluetoothDevicesDiscovery:ok") {
					BLData.BLZT = true;
					BLData.TS = "开始搜索蓝牙设备";
					//监听搜索到新设备事件
					uni.onBluetoothDeviceFound(function(res) {
						var SB = {
							name: "",
							id: "",
							tp: "",
							dis: false,
							status: 0, //0列表 1连接中 2已连接
							disconnect: 0, //无操作，1手动断开
							LJOK: "0"
						};
						BLData.TS = "搜索到蓝牙设备";
						if (res.devices[0].localName == "" || !res.devices[0].localName) {
							return;
						}
						if (chongfu(res.devices[0].deviceId, res.devices[0].RSSI)) {
							return;
						}
						SB.name = res.devices[0].localName;
						SB.id = res.devices[0].deviceId;
						SB.strength = check_strength(res.devices[0].RSSI)
						SB.dis = false;
						BLSB.push(SB)
						onDeviceFound(res)
						console.log("新增设备:", res, SB)
					})
				}
			}
		})
		if (option.hasOwnProperty('duration')) {
			setTimeout(function(res) {
				stopsearch()
			}, option.duration)
		}

	})
}

function check_strength(xh) {
	if (xh > -50) {
		return 5
	} else if (xh > -70) {
		return 4
	} else if (xh > -80) {
		return 3
	} else if (xh > -90) {
		return 2
	} else {
		return 1
	}
}
// 已经搜索到的蓝牙操作
function chongfu(uuid, RSSI) {
	var iscf = false;
	for (var x in BLSB) {
		if (BLSB[x].id == uuid) {
			BLSB[x].strength = check_strength(RSSI)
			iscf = true
		}
	}
	return iscf;
}

// 停止搜索
function stopsearch(callback = '') {
	if (BLData.BLSO == false) {
		if (callback != '') {
			callback()
		}
	}
	BLData.BLSO = false
	console.log('停止搜索蓝牙')
	uni.stopBluetoothDevicesDiscovery({
		success() {
			if (callback != '') {
				callback()
			}
		},
		fail: function(res) {
			console.log("停止搜索失败:", res)
		}
	})
}
var connect_num = 0

// 判断设备是否连接
function check_donnect_status(dore) {
	let bool = true
	if (connectInfo == null || dayinji.status == 0) {
		bool = false
	}
	return bool
}
// 连接设备
function connect(info, callback = '') {
	if (lianjieing == true) {
		if (callback != '') {
			callback("正在尝试连接,请稍后再试");
			BLData.TS = '正在尝试连接,请稍后再试'
		}
		return;
	}

	if (connectInfo != null) {
		console.log("已有链接");
		return disconnect(info)
	}
	lianjieing = true
	connectInfo = null //连接中的蓝牙
	dayinji = {
		status: 0,
		uuid: "",
		suuid: "",
		nuuid: ""
	} //已连接的蓝牙设备 uuid
	info = set_devices(info, 'disconnect', 0)
	info = set_status(info, 1)
	connect_num = 0
	doconnect(info, callback)
}
// 连接设备操作
var statechange = false

function doconnect(info, callback = '') {
	connect_num++
	let s = "第" + connect_num + "次尝试连接"
	BLData.TS = s
	console.log(s)
	uni.createBLEConnection({
		deviceId: info.id,
		success: function(res) {
			console.log("连接成功.第" + connect_num + "次:", res)
			BLData.TS = "连接成功"
			info = set_status(info, 2)
			connectInfo = info
			stopsearch()
			uni.onBLEConnectionStateChange(function(res) {
				if (res.connected == false && connectInfo != null && connectInfo.disconnect != 1) {
					console.log("监测到断开,自动重连", info);
					connect(info)
				}
			})
			if (callback != '') {
				callback(true);
			}
		},
		fail: function(res) {
			console.log("连接失败:", res)
			BLData.TS = "连接失败"
			if (connect_num >= 3) {
				info = set_status(info, 0)
				lianjieing = false; //已经不在尝试连接了
				if (callback != '') {
					BLData.TS = '连接失败,请重新配置打印机'
					callback("连接失败,请重新配置打印机");
				}
			} else {
				doconnect(info, callback); //再次尝试连接
			}
		}
	})
}

function set_devices(info, key, value) {
	var bool = info == 'all'

	for (var x in BLSB) {
		if (!bool && BLSB[x].id == info.id) {
			BLSB[x][key] = value
			return BLSB[x]
		}
		if (bool) {
			BLSB[x][key] = value
		}
	}
}

function set_status(info, value) {
	return set_devices(info, 'status', value)
}

// 断开连接
function disconnect(info, callback = '', reconnect = false) {
	console.log("断开连接", info, callback = '', reconnect = false);
	info = set_devices(info, 'disconnect', 1)
	connectInfo.disconnect = 1
	BLData.TS = '断开连接'
	uni.closeBLEConnection({
		deviceId: connectInfo.id,
		success: function(res) {
			connectInfo = null
			dayinji = {
				status: 0,
				uuid: "",
				suuid: "",
				nuuid: ""
			}
			set_status('all', 0)
			if (callback != '') {
				callback()
			}
		},
		fail(res) {
			uni.getConnectedBluetoothDevices({
				success(res) {
					console.log(res)
				}
			})
		}
	})
}


// 获取蓝牙服务
function getServices(callback) {
	uni.getBLEDeviceServices({
		deviceId: connectInfo.id,
		success: function(res) {
			console.log("所有服务:", res)
			for (var p in res.services) {
				if (dayinji.status == 1) break;
				getCharacteristics(res.services[p].uuid, callback); //开始获取特征吗       
			}
			setTimeout(function(){
				lianjieing = false;
			},5000)
		},
		fail(res) {
			console.log(res)
		}
	})
}

function setdayinji(info) {
	dayinji = info
	console.log("AA当前打印机:uuid:" + dayinji.uuid + "suuid:" + dayinji.suuid + "nuuid:" +
		dayinji.nuuid);
}
// 获取服务的特征characteristic
function getCharacteristics(xsuuid, callback) {
	if (dayinji.status == 1) return;
	var xuuid = connectInfo.id
	uni.getBLEDeviceCharacteristics({
		deviceId: xuuid,
		serviceId: xsuuid,
		success: function(res) {
			for (var p in res.characteristics) {
				var rr = res.characteristics[p].properties
				console.log(rr);
				if (rr.notify && rr.write) {
					setdayinji({
						uuid: xuuid,
						suuid: xsuuid,
						nuuid: res.characteristics[p].uuid,
						status: 1
					})
					lianjieing = false;
					uni.setStorage({
						key: "dayinji",
						data: dayinji
					})
					callback(dayinji.status == 1);
					break;
				}
			}
			
		}
	})
}



function zdlianjie() {
	try {
		var value = uni.getStorageSync('dayinji')
		if (value) {
			uni.openBluetoothAdapter({
				success: function(res) {
					lianjie(value.uuid, function(re) {});
				},
				fail: function(res) {
					BLData.TS = "请先打开蓝牙开关!"
				}
			})
		}
	} catch (e) {
		console.log("读取缓存数据错误:", e)
	}
}

module.exports = {
	dayinji: function(){
		return dayinji
	}, //连接的打印机信息
	GETData: GETData,
	GETSB: GETSB,
	GetconnectInfo: function() {
		return connectInfo
	},
	zdlj: zdlianjie,
	chonglian: chonglian,
	openBlueTooth: openBlueTooth,
	checkBluetoothAdapterState: checkBluetoothAdapterState,
	searchDevices: searchDevices,
	stopsearch: stopsearch,
	connect: connect,
	disconnect: disconnect,
	getServices: getServices,
	reset: reset,
	check_donnect_status: check_donnect_status
};